{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Critical Points and Optimization\n",
    "We've explored various techniques that we can use to calculate the derivative of a function at a specific *x* value; in other words, we can determine the *slope* of the line created by the function at any point on the line.\n",
    "\n",
    "This ability to calculate the slope means that we can use derivatives to determine some interesting properties of the function.\n",
    "\n",
    "## Function Direction at a Point\n",
    "Consider the following function, which represents the trajectory of a ball that has been kicked on a football field:\n",
    "\n",
    "\\begin{equation}k(x) = -10x^{2} + 100x + 3 \\end{equation}\n",
    "\n",
    "Run the Python code below to graph this function and see the trajectory of the ball over a period of 10 seconds."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function k\n",
    "def k(x):\n",
    "    return -10*(x**2) + (100*x)  + 3\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(0, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [k(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x (time in seconds)')\n",
    "plt.ylabel('k(x) (height in feet)')\n",
    "plt.xticks(range(0,15, 1))\n",
    "plt.yticks(range(-200, 500, 20))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By looking at the graph of this function, you can see that it describes a parabola in which the ball rose in height before falling back to the ground. On the graph, it's fairly easy to see when the ball was rising and when it was falling.\n",
    "\n",
    "Of course, we can also use  derivative to determine the slope of the function at any point. We can apply some of the rules we've discussed previously to determine the derivative function:\n",
    "\n",
    "- We can add together the derivatives of the individual terms (***-10x<sup>2</sup>***, ***100x***, and ***3***) to find the derivative of the entire function.\n",
    "- The *power* rule tells us that the derivative of ***-10x<sup>2</sup>*** is ***-10 &bull; 2x***, which is ***-20x***.\n",
    "- The *power* rule also tells us that the derivative of ***100x*** is ***100***.\n",
    "- The derivative of any constant, such as ***3*** is ***0***.\n",
    "\n",
    "So:\n",
    "\n",
    "\\begin{equation}k'(x) = -20x + 100 + 0 \\end{equation}\n",
    "\n",
    "Which of course simplifies to:\n",
    "\n",
    "\\begin{equation}k'(x) = -20x + 100 \\end{equation}\n",
    "\n",
    "Now we can use this derivative function to find the slope for any value of ***x***.\n",
    "\n",
    "Run the cell below to see a graph of the function and its derivative function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function k\n",
    "def k(x):\n",
    "    return -10*(x**2) + (100*x)  + 3\n",
    "\n",
    "def kd(x):\n",
    "    return -20*x + 100\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(0, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [k(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the derivative values\n",
    "yd = [kd(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x (time in seconds)')\n",
    "plt.ylabel('k(x) (height in feet)')\n",
    "plt.xticks(range(0,15, 1))\n",
    "plt.yticks(range(-200, 500, 20))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "# Plot the derivative\n",
    "plt.plot(x,yd, color='purple')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Look closely at the purple line representing the derivative function, and note that it is a constant  decreasing value - in other words, the slope of the function is reducing linearly as x increases. Even though the function value itself is increasing for the first half of the parabola (while the ball is rising), the slope is becoming less steep (the ball is not rising at such a high rate), until finally the ball reaches its apogee and the slope becomes negative (the ball begins falling).\n",
    "\n",
    "Note also that the point where the derivative line crosses 0 on the y-axis is also the point where the function value stops increasing and starts decreasing. When the slope has a positive value, the function is increasing; and when the slope has a negative value, the function is decreasing.\n",
    "\n",
    "The fact that the derivative line crosses 0 at the highest point of the function makes sense if you think about it logically. If you were to draw the tangent line representing the slope at each point, it would be rotating clockwise throughout the graph, initially pointing up and to the right as the ball rises, and turning until it is pointing down and right as the ball falls. At the highest point, the tangent line would be perfectly horizontal, representing a slope of 0.\n",
    "\n",
    "Run the following code to visualize this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function k\n",
    "def k(x):\n",
    "    return -10*(x**2) + (100*x)  + 3\n",
    "\n",
    "def kd(x):\n",
    "    return -20*x + 100\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(0, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [k(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the derivative values\n",
    "yd = [kd(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x (time in seconds)')\n",
    "plt.ylabel('k(x) (height in feet)')\n",
    "plt.xticks(range(0,15, 1))\n",
    "plt.yticks(range(-200, 500, 20))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "# Plot the derivative\n",
    "plt.plot(x,yd, color='purple')\n",
    "\n",
    "# Plot tangent slopes for x = 2, 5, and 8\n",
    "x1 = 2\n",
    "x2 = 5\n",
    "x3 = 8\n",
    "plt.plot([x1-1,x1+1],[k(x1)-(kd(x1)),k(x1)+(kd(x1))], color='red')\n",
    "plt.plot([x2-1,x2+1],[k(x2)-(kd(x2)),k(x2)+(kd(x2))], color='red')\n",
    "plt.plot([x3-1,x3+1],[k(x3)-(kd(x3)),k(x3)+(kd(x3))], color='red')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now consider the following function, which represents the number of flowers growing in a flower bed before and after the spraying of a fertilizer:\n",
    "\n",
    "\\begin{equation}w(x) = x^{2} + 2x + 7 \\end{equation}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function w\n",
    "def w(x):\n",
    "    return (x**2) + (2*x) + 7\n",
    "\n",
    "def wd(x):\n",
    "    return 2*x + 2\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(-10, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [w(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the derivative values\n",
    "yd = [wd(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x (time in days)')\n",
    "plt.ylabel('w(x) (flowers)')\n",
    "plt.xticks(range(-10,15, 1))\n",
    "plt.yticks(range(-200, 500, 20))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "# Plot the derivative\n",
    "plt.plot(x,yd, color='purple')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the green line represents the function, showing the number of flowers for 10 days before and after the fertilizer treatment. Before treatment, the number of flowers was in decline, and after treatment the flower bed started to recover.\n",
    "\n",
    "The derivative function is shown in purple, and once again shows a linear change in slope. This time, the slope is increasing at a constant rate; and once again, the derivative function line crosses 0 at the lowest point in the function line (in other words, the slope changed from negative to positive when the flowers started to recover)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Critical Points\n",
    "From what we've seen so far, it seems that there is a relationship between a function reaching an extreme value (a maximum or a minimum), and a derivative value of 0. This makes intuitive sense; the derivative represents the slope of the line, so when a function changes from a negative slope to a positive slope, or vice-versa, the derivative must pass through 0.\n",
    "\n",
    "However, you need to be careful not to assume that just because the derivative is 0 at a given point, that this point represents the minimum or maximum of the function. For example, consider the following function:\n",
    "\n",
    "\\begin{equation}v(x) = x^{3} - 2x + 100 \\end{equation}\n",
    "\n",
    "Run the following Python code to visualize this function and its corresponding derivative function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function v\n",
    "def v(x):\n",
    "    return (x**3) - (2*x) + 100\n",
    "\n",
    "def vd(x):\n",
    "    return 3*(x**2) - 2\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(-10, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [v(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the derivative values\n",
    "yd = [vd(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('v(x)')\n",
    "plt.xticks(range(-10,15, 1))\n",
    "plt.yticks(range(-1000, 2000, 100))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "# Plot the derivative\n",
    "plt.plot(x,yd, color='purple')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that in this case, the purple derivative function line passes through 0 as the green function line transitions from a *concave downwards* slope (a slope that is decreasing) to a *concave upwards* slope (a slope that is increasing). The slope flattens out to 0, forming a \"saddle\" before the it starts increasing.\n",
    "\n",
    "What we can learn from this is that interesting things seem to happen to the function when the derivative is 0. We call points where the derivative crosses 0 *critical points*, because they indicate that the function is changing direction. When a function changes direction from positive to negative, it forms a peak (or a *local maximum*), when the function changes direction from negative to positive it forms a trough (or *local minimum*), and when it maintains the same overall direction but changes the concavity of the slope it creates an *inflexion point*."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Finding Minima and Maxima\n",
    "A common use of calculus is to find minimum and maximum points in a function. For example, we might want to find out how many seconds it took for the kicked football to reach its maximum height, or how long it took for our fertilizer to be effective in reversing the decline of flower growth.\n",
    "\n",
    "We've seen that when a function changes direction to create a maximum peak or a minimum trough, the derivative of the function is 0, so a step towards finding these extreme points might be to simply find all of the points in the function where the derivative is 0. For example, here's our function for the kicked football:\n",
    "\n",
    "\\begin{equation}k(x) = -10x^{2} + 100x + 3 \\end{equation}\n",
    "\n",
    "From this, we've calculated the function for the derivative as:\n",
    "\n",
    "\\begin{equation}k'(x) = -20x + 100 \\end{equation}\n",
    "\n",
    "We can then solve the derivative equation for an f'(x) value of 0:\n",
    "\n",
    "\\begin{equation}-20x + 100 = 0 \\end{equation}\n",
    "\n",
    "We can remove the constant by subtracting 100 to both sides:\n",
    "\n",
    "\\begin{equation}-20x = -100 \\end{equation}\n",
    "\n",
    "Multiplying both sides by -1 gets rid of the negative values (this isn't strictly necessary, but makes the equation a little less confusing)\n",
    "\n",
    "\\begin{equation}20x = 100 \\end{equation}\n",
    "\n",
    "So:\n",
    "\n",
    "\\begin{equation}x = 5 \\end{equation}\n",
    "\n",
    "So we know that the derivative will be 0 when *x* is 5, but is this a minimum, a maximum, or neither? It could just be an inflexion point, or the entire function could be a constant value with a slope of 0) Without looking at the graph, it's difficult to tell.\n",
    "\n",
    "## Second Order Derivatives\n",
    "The solution to our problem is to find the derivative of the derivative! Until now, we've found the derivative of a function, and indicated it as ***f'(x)***. Technically, this is known as the *prime* derivative; and it describes the slope of the function. Since the derivative function is itself a function, we can find its derivative, which we call the *second order* (or sometimes just *second*) derivative. This is indicated like this: ***f''(x)***.\n",
    "\n",
    "So, here's our function for the kicked football:\n",
    "\n",
    "\\begin{equation}k(x) = -10x^{2} + 100x + 3 \\end{equation}\n",
    "\n",
    "Here's the function for the prime derivative:\n",
    "\n",
    "\\begin{equation}k'(x) = -20x + 100 \\end{equation}\n",
    "\n",
    "And using a combination of the power rule and the constant rule, here's the function for the second derivative:\n",
    "\n",
    "\\begin{equation}k''(x) = -20 \\end{equation}\n",
    "\n",
    "Now, without even drawing the graph, we can see that the second derivative has a constant value; so we know that the slope of the prime derivative is linear; and because it's a negative value, we know that it is decreasing. So when the prime derivative crosses 0, it we know that the slope of the function is decreasing linearly; so the point at *x=0* must be a maximum point.\n",
    "\n",
    "Run the following code to plot the function, the prime derivative, and the second derivative for the kicked ball:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function k\n",
    "def k(x):\n",
    "    return -10*(x**2) + (100*x)  + 3\n",
    "\n",
    "def kd(x):\n",
    "    return -20*x + 100\n",
    "\n",
    "def k2d(x):\n",
    "    return -20\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(0, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [k(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the k'(x) values\n",
    "yd = [kd(i) for i in x]\n",
    "\n",
    "# Use the 2-derivative function to get the k''(x)\n",
    "y2d = [k2d(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x (time in seconds)')\n",
    "plt.ylabel('k(x) (height in feet)')\n",
    "plt.xticks(range(0,15, 1))\n",
    "plt.yticks(range(-200, 500, 20))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "# Plot  k'(x)\n",
    "plt.plot(x,yd, color='purple')\n",
    "\n",
    "# Plot k''(x)\n",
    "plt.plot(x,y2d, color='magenta')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's take the same approach for the flower bed problem. Here's the function:\n",
    "\n",
    "\\begin{equation}w(x) = x^{2} + 2x + 7 \\end{equation}\n",
    "\n",
    "Using the power rule and constant rule, gives us the prime derivative function:\n",
    "\n",
    "\\begin{equation}w'(x) = 2x + 2 \\end{equation}\n",
    "\n",
    "Applying the power rule and constant rule to the prime derivative function gives us the second derivative function:\n",
    "\n",
    "\\begin{equation}w''(x) = 2 \\end{equation}\n",
    "\n",
    "Note that this time, the second derivative is a positive constant, so the prime derivative (which is the slope of the function) is increasing linearly. The point where the prime derivative crosses 0 must therefore be a minimum. Let's run the code below to check:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function w\n",
    "def w(x):\n",
    "    return (x**2) + (2*x) + 7\n",
    "\n",
    "def wd(x):\n",
    "    return 2*x + 2\n",
    "\n",
    "def w2d(x):\n",
    "    return 2\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(-10, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [w(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the w'(x) values\n",
    "yd = [wd(i) for i in x]\n",
    "\n",
    "# Use the 2-derivative function to get the w''(x) values\n",
    "y2d = [w2d(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x (time in days)')\n",
    "plt.ylabel('w(x) (flowers)')\n",
    "plt.xticks(range(-10,15, 1))\n",
    "plt.yticks(range(-200, 500, 20))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "# Plot w'(x)\n",
    "plt.plot(x,yd, color='purple')\n",
    "\n",
    "# Plot w''(x)\n",
    "plt.plot(x,y2d, color='magenta')\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Critical Points that are *Not* Maxima or Minima\n",
    "Of course, it's possible for a function to form a \"saddle\" where the prime derivative is zero at a point that is not a minimum or maximum. Here's an example of a function like this:\n",
    " \n",
    "\\begin{equation}v(x) = x^{3} - 6x^{2} + 12x + 2 \\end{equation}\n",
    "\n",
    "And here's its prime derivative:\n",
    " \n",
    "\\begin{equation}v'(x) = 3x^{2} - 12x + 12 \\end{equation}\n",
    " \n",
    "Let's find a critical point where v'(x) = 0\n",
    " \n",
    "\\begin{equation}3x^{2} - 12x + 12 = 0 \\end{equation}\n",
    "\n",
    "Factor the x-terms\n",
    " \n",
    "\\begin{equation}3x(x - 4) = 12 \\end{equation}\n",
    "\n",
    "Divide both sides by 3:\n",
    "\n",
    "\\begin{equation}x(x - 4) = 4 \\end{equation}\n",
    "\n",
    "Factor the x terms back again\n",
    "\n",
    "\\begin{equation}x^{2} - 4x = 4 \\end{equation}\n",
    "\n",
    "Complete the square, step 1\n",
    "\n",
    "\\begin{equation}x^{2} - 4x + 4 = 0 \\end{equation}\n",
    "\n",
    "Complete the square, step 2\n",
    "\n",
    "\\begin{equation}(x - 2)^{2} = 0 \\end{equation}\n",
    "\n",
    "Find the square root:\n",
    "\n",
    "\\begin{equation}x - 2 = \\pm\\sqrt{0}\\end{equation}\n",
    "\n",
    "\\begin{equation}x - 2 = +\\sqrt{0} = 0, -\\sqrt{0} = 0\\end{equation}\n",
    "\n",
    "v'(2) = 0 (only touches 0 once)\n",
    "\n",
    "Is it a maximum or minimum? Let's find the second derivative:\n",
    "\n",
    "\\begin{equation}v''(x) = 6x - 12\\end{equation}\n",
    "\n",
    "So\n",
    "\n",
    "\\begin{equation}v''(2) = 0\\end{equation}\n",
    "\n",
    "So it's neither negative or positive, so it's not a maximum or minimum."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function v\n",
    "def v(x):\n",
    "    return (x**3) - (6*(x**2)) + (12*x) + 2\n",
    "\n",
    "def vd(x):\n",
    "    return (3*(x**2)) - (12*x) + 12\n",
    "\n",
    "def v2d(x):\n",
    "    return (3*(2*x)) - 12\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(-5, 11))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [v(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the derivative values\n",
    "yd = [vd(i) for i in x]\n",
    "\n",
    "# Use the derivative function to get the derivative values\n",
    "y2d = [v2d(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x')\n",
    "plt.ylabel('v(x)')\n",
    "plt.xticks(range(-10,15, 1))\n",
    "plt.yticks(range(-2000, 2000, 50))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "# Plot the derivative\n",
    "plt.plot(x,yd, color='purple')\n",
    "\n",
    "# Plot the derivative\n",
    "plt.plot(x,y2d, color='magenta')\n",
    "\n",
    "plt.show()\n",
    "\n",
    "print (\"v(2) = \" + str(v(2)))\n",
    "\n",
    "print (\"v'(2) = \" + str(vd(2)))\n",
    "\n",
    "print (\"v''(2) = \" + str(v2d(2)))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Optimization\n",
    "The ability to use derivatives to find minima and maxima of a function makes it a useful tool for scenarios where you need to optimize a function for a specific variable.\n",
    "\n",
    "### Defining Functions to be Optimized\n",
    "For example, suppose you have decided to build an online video service that is based on a subscription model. You plan to charge a monthly subscription fee, and you want to make the most revenue possible. The problem is that customers are price-sensitive, so if you set the monthly fee too high, you'll deter some customers from signing up. Conversely, if you set the fee too low, you may get more customers, but at the cost of reduced revenue.\n",
    "\n",
    "What you need is some kind of function that will tell you how many subscriptions you might expect to get based on a given fee. So you've done some research, and found a formula to indicate that the expected subscription volume (in thousands) can be calculated as 5-times the monthly fee subtracted from 100; or expressed as a function:\n",
    "\n",
    "\\begin{equation}s(x) = -5x + 100\\end{equation}\n",
    "\n",
    "What you actually want to optimize is monthly revenue, which is simply the number of subscribers multiplied by the fee:\n",
    "\n",
    "\\begin{equation}r(x) = s(x) \\cdot x\\end{equation}\n",
    "\n",
    "We can combine ***s(x)*** into ***r(x)*** like this:\n",
    "\n",
    "\\begin{equation}r(x) = -5x^{2} + 100x\\end{equation}\n",
    "\n",
    "### Finding the Prime Derivative\n",
    "The function ***r(x)*** will return the expected monthly revenue (in thousands) for any proposed fee (*x*). What we need to do now is to find the fee that yields the maximum revenue. Fortunately, we can use a derivative to do that.\n",
    "\n",
    "First, we need to determine the prime derivative of ***r(x)***, and we can do that easily using the power rule:\n",
    "\n",
    "\\begin{equation}r'(x) = 2 \\cdot -5x + 100\\end{equation}\n",
    "\n",
    "Which is:\n",
    "\n",
    "\\begin{equation}r'(x) = -10x + 100\\end{equation}\n",
    "\n",
    "### Find Critical Points\n",
    "Now we need to find any critical points where the derivative is 0, as this could indicate a maximum:\n",
    "\n",
    "\\begin{equation}-10x + 100 = 0\\end{equation}\n",
    "\n",
    "Let's isolate the *x* term:\n",
    "\n",
    "\\begin{equation}-10x = -100\\end{equation}\n",
    "\n",
    "Both sides are negative, so we can mulitply both by -1 to make them positive without affecting the equation:\n",
    "\n",
    "\\begin{equation}10x = 100\\end{equation}\n",
    "\n",
    "Now we can divide both sides by 10 to isolate *x*:\n",
    "\n",
    "\\begin{equation}x = \\frac{100}{10}\\end{equation}\n",
    "\n",
    "So:\n",
    "\n",
    "\\begin{equation}x = 10\\end{equation}\n",
    "\n",
    "#### Check for a Maximum\n",
    "We now know that with an *x* value of of **10**, the derivative is 0; or put another way, when the fee is 10, the slope indicating the change in subscription volume is flat. This could potentially be a point where the change in subscription volume has peaked (in other words, a maximum); but it could also be a minimum or just an inflexion point where the rate of change transitions from negative to positive.\n",
    "\n",
    "To be sure, we can check the second order derivative. We can calculate this by applying the power rule to the prime derivative:\n",
    "\n",
    "\\begin{equation}r''(x) = -10\\end{equation}\n",
    "\n",
    "Note that the second derivative is a constant with a negative value. It will be the same for any point, including our critical point at *x=10*:\n",
    "\n",
    "\\begin{equation}r''(10) = -10\\end{equation}\n",
    "\n",
    "A negative value for the second derivative tells us that the derivative slope is moving in a negative direction at the point where it is 0, so the function value must be at a maximum.\n",
    "\n",
    "In other words, the optimal monthly fee for our online video service is 10 - this will generate the maximum monthly revenue.\n",
    "\n",
    "Run the code below to show the function ***r(x)*** as a graph, and verify that the maximum point is at x = 10."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "# Create function s\n",
    "def s(x):\n",
    "    return (-5*x) + 100\n",
    "\n",
    "# Create function r\n",
    "def r(x):\n",
    "    return s(x) * x\n",
    "\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "# Create an array of x values to plot\n",
    "x = list(range(0, 21))\n",
    "\n",
    "# Use the function to get the y values\n",
    "y = [r(i) for i in x]\n",
    "\n",
    "# Set up the graph\n",
    "plt.xlabel('x (monthly fee)')\n",
    "plt.ylabel('r(x) (revenue in $,000)')\n",
    "plt.xticks(range(0,22, 1))\n",
    "plt.yticks(range(0, 600, 50))\n",
    "plt.grid()\n",
    "\n",
    "# Plot the function\n",
    "plt.plot(x,y, color='green')\n",
    "\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.6",
   "language": "python",
   "name": "python36"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
